package com.chain.BrotherExchange.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.chain.BrotherExchange.C;
import com.chain.BrotherExchange.R;
import com.chain.BrotherExchange.data.Resource;
import com.chain.BrotherExchange.data.model.LegalTenderDealList;
import com.chain.BrotherExchange.data.model.UserPayment;
import com.chain.BrotherExchange.event.SubmitAlipayEvent;
import com.chain.BrotherExchange.event.SubmitBankCardEvent;
import com.chain.BrotherExchange.event.SubmitPayPalEvent;
import com.chain.BrotherExchange.event.SubmitRealNameAuthenticationEvent;
import com.chain.BrotherExchange.event.SubmitWeChatPayEvent;
import com.chain.BrotherExchange.event.UserAssetsChangeEvent;
import com.chain.BrotherExchange.ui.adapter.TextWatcherAdapter;
import com.chain.BrotherExchange.ui.core.BaseActivity;
import com.chain.BrotherExchange.utils.ActivityBarHelper;
import com.chain.BrotherExchange.utils.Androids;
import com.chain.BrotherExchange.utils.ViewUtils;
import com.chain.BrotherExchange.viewmodel.IDAuthenticationViewModel;
import com.chain.BrotherExchange.viewmodel.LegalTenderAddOrderViewModel;
import com.chain.BrotherExchange.viewmodel.PaymentViewModel;
import com.chain.BrotherExchange.viewmodel.core.ViewModelProviders;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.Serializable;

import butterknife.Bind;

/**
 * 法币交易购买/出售
 */
public class LegalTenderBuyOrSellActivity extends BaseActivity {

    @Bind(R.id.apply_button) Button mApplyButton;
    @Bind(R.id.arrow_back_image) View mArrowBackImageView;
    @Bind(R.id.unit_price_text) TextView mUnitPriceTextView;
    @Bind(R.id.quota_price_text) TextView mQuotaPriceTextView;
    @Bind(R.id.token_symbol_text) TextView mTokenSymbolTextView;
    @Bind(R.id.small_token_symbol_text) TextView smallTokenSymbolText;
    @Bind(R.id.max_purchased_number_text) TextView maxPurchasedNumberText;
    @Bind(R.id.purchased_total_value_edit) EditText purchasedTotalValueEdit;
    @Bind(R.id.purchased_number_edit_text) EditText purchasedNumberEditText;

    private int mPageType;
    private boolean setPaymentMethod;
    private PaymentViewModel mPaymentViewModel;
    int authenticationState = C.API_UNAUTHORIZED;
    private LegalTenderAddOrderViewModel mViewModel;
    private UserPayment.DataBean.SetpaysBean mSetpays;
    private LegalTenderDealList.DataBean.ListBean mBean;
    private IDAuthenticationViewModel mIdAuthenticationViewModel;

    public static void launch(Context context, int type, Serializable serializable) {
        context.startActivity(new Intent(context, LegalTenderBuyOrSellActivity.class)
                .putExtra(C.EXTRA_PAGE_TYPE, type)
                .putExtra(C.SERIALIZABLE_ORDER, serializable)
        );
    }

    @Override
    protected boolean useEventBus() {
        return true;
    }

    @Override
    protected void setStatusBar() {
        ActivityBarHelper.setTransparentStatus(this);
    }

    @Override
    protected int getLayoutID() {
        return R.layout.activity_legal_currency_buy_or_sell;
    }

    @Override
    protected void initActions() {
        mPageType = getIntent().getIntExtra(C.EXTRA_PAGE_TYPE, -1);
        mBean = (LegalTenderDealList.DataBean.ListBean)
                getIntent().getSerializableExtra(C.SERIALIZABLE_ORDER);

        switch (mPageType) {
            case C.API_PURCHASE:
                initPurchaseView();
                break;
            case C.API_SELL:
                initSellView();
                break;
        }

        mPaymentViewModel = ViewModelProviders.of(this).get(PaymentViewModel.class);
        mViewModel = ViewModelProviders.of(this).get(LegalTenderAddOrderViewModel.class);
        mIdAuthenticationViewModel = ViewModelProviders.of(this).get(IDAuthenticationViewModel.class);
        mArrowBackImageView.setOnClickListener(v -> onBackPressed());
        mUnitPriceTextView.setText(getString(R.string.unit_price) + mBean.getPriceText());
        mTokenSymbolTextView.setText(mBean.getToken_name());
        smallTokenSymbolText.setText(mBean.getToken_name());
        mQuotaPriceTextView.setText(getString(R.string.quota) + mBean.getMinLimitText() + "-" + mBean.getMaxLimitText() + "CNY");

        // 获取支付状态
        initPayment();

        // 获取验证状态
        initAuthentication();

        // 设置单价
        mViewModel.setUnitPrice(mBean.getPrice());

        // 设置总量
        purchasedTotalValueEdit.addTextChangedListener(new TextWatcherAdapter(text -> {
            mViewModel.setTotalPrice(text.toString());
        }));

        // 设置数量
        purchasedNumberEditText.addTextChangedListener(new TextWatcherAdapter(text -> {
            mViewModel.setTransactionNumber(text.toString());
        }));

        // 获取总量
        mViewModel.getTotalPrice().observe(this, totalPrice ->
                ViewUtils.setTextAndSelectionEnd(totalPrice, purchasedTotalValueEdit)
        );

        // 获取数量
        mViewModel.getTransactionNumber().observe(this, number ->
                ViewUtils.setTextAndSelectionEnd(number, purchasedNumberEditText)
        );

        // 购买/出售
        mApplyButton.setOnClickListener(v -> publishAddOrder());
    }

    // 发布订单
    private void publishAddOrder() {
        if (!Androids.LocalConfig.isSetTransactionPassword()) {
            new AlertDialog.Builder(this).setTitle(R.string.improve_information)
                    .setMessage(R.string.dialog_fund_password)
                    .setPositiveButton(R.string.go_setting, (dialog, which) ->
                            SettingTransactionPasswordActivity.launch(this)
                    ).setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss()).show();
        } else if (setPaymentMethod) {
            new AlertDialog.Builder(this).setTitle(R.string.improve_information)
                    .setMessage(R.string.dialog_payment)
                    .setPositiveButton(R.string.go_setting, (dialog, which) ->
                            PaymentActivity.launch(this)
                    ).setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss()).show();
        } else if (authenticationState == C.API_UNAUTHORIZED || authenticationState == C.API_AUTHENTICATION_FAILURE) {
            new AlertDialog.Builder(this).setTitle(R.string.improve_information)
                    .setMessage(R.string.dialog_secondary_certification)
                    .setPositiveButton(R.string.go_setting, (dialog, which) ->
                            PersonalCenterActivity.launch(this)
                    ).setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss()).show();
        } else if (authenticationState == C.API_IN_AUTHENTICATION) {
            Androids.makeText(R.string.message_secondary_certification_ing);
        } else {
            addOrder();
        }
    }

    private void initPayment(){
        // 用户支付方式
        mPaymentViewModel.userPayment().observe(this, resource -> {
            if (resource.state == Resource.Status.SUCCESS) {
                mSetpays = resource.source.getSetpays();
                setPaymentMethod = mSetpays.isSetPayment();
            }
        });
    }

    private void initAuthentication(){
        mIdAuthenticationViewModel.isAuthentication().observe(this, resource -> {
            if (resource.state == Resource.Status.SUCCESS) {
                authenticationState = resource.source.getCheck_mark_second();
            }
        });
    }

    private void addOrder() {
        String number = purchasedNumberEditText.getText().toString();
        mViewModel.addOrder(mBean.getId(), number).observe(this, resource -> {
            if (resource.state == Resource.Status.LOADING) {
                Androids.showProgressMessage(this, "");
            } else {
                Androids.dismissProgressMessage();
                Androids.makeText(resource.message);
                if (resource.state == Resource.Status.SUCCESS) {

                    // 跳转订单详情
                    if (mPageType == C.API_PURCHASE) {
                        LegalTenderBuyOrderDetailsActivity.launch(this, resource.source.getId());
                    } else if (mPageType == C.API_SELL) {
                        LegalTenderSellOrderDetailsActivity.launch(this, resource.source.getId());
                    }

                    // 关闭页面, 用户资产改变事件
                    finish();
                    EventBus.getDefault().post(new UserAssetsChangeEvent());
                }
            }
        });
    }

    private void initSellView() {
        mApplyButton.setText(R.string.text_confirm_sale);
        purchasedTotalValueEdit.setHint(R.string.hint_please_enter_total_amount_sell);
        purchasedNumberEditText.setHint(R.string.hint_please_enter_quantity_sell);
        maxPurchasedNumberText.setText(getString(R.string.text_maximum_quantity_available_sale)
                + mBean.getNumText() + mBean.getToken_name());
    }

    private void initPurchaseView() {
        mApplyButton.setText(R.string.confirm_purchase);
        purchasedTotalValueEdit.setHint(R.string.hint_please_enter_total_amount_purchase);
        purchasedNumberEditText.setHint(R.string.hint_please_enter_quantity_purchase);
        maxPurchasedNumberText.setText(getString(R.string.text_maximum_quantity_available_purchase)
                + mBean.getNumText() + mBean.getToken_name());
    }

    @Subscribe
    public void addBankCardEvent(SubmitBankCardEvent event) {
        if (mSetpays != null) {
            mSetpays.setBank_pay(1);
            setPaymentMethod = false;
        }
    }

    @Subscribe
    public void addPayPalEvent(SubmitPayPalEvent event) {
        if (mSetpays != null) {
            mSetpays.setPaypal_pay(1);
            setPaymentMethod = false;
        }
    }

    @Subscribe
    public void addAliPayEvent(SubmitAlipayEvent event) {
        if (mSetpays != null) {
            mSetpays.setAli_pay(1);
            setPaymentMethod = false;
        }
    }

    @Subscribe
    public void addWeChatPay(SubmitWeChatPayEvent event) {
        if (mSetpays != null) {
            mSetpays.setWechat_pay(1);
            setPaymentMethod = false;
        }
    }

    @Subscribe
    public void submitRealNameAuthenticationEvent(SubmitRealNameAuthenticationEvent event) {
        if (event.state == C.API_AUTHENTICATION_SUCCESS) {
            authenticationState = C.API_AUTHENTICATION_SUCCESS;
        } else {
            authenticationState = C.API_IN_AUTHENTICATION;
            initAuthentication();
        }
    }
}
